02. Spring Boot Exception- @ControllerAdvise + @ExceptionHandler
035ND C01 L04 A05 @CONTROLLERADVICE + @EXCEPTIONHANDLER
Instructions
Add a new controller named RoleController class under controller directory.
@Controller
public class RoleController {
@RequestMapping("/roleadd")
public String add() {
int num = 10 / 0;
return "add";
}
}
Create an exceptions folder, Create a GolbalExceptionHandler class in it.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value={java.lang.ArithmeticException.class})
public ModelAndView handlerArithmeticException(Exception e) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("exception", e.toString());
modelAndView.setViewName("mathError");
return modelAndView;
}
@ExceptionHandler(value={java.lang.NullPointerException.class})
public ModelAndView handlerNullPointerException(Exception e) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("exception", e.toString());
modelAndView.setViewName("nullPointerError");
return modelAndView;
}
}
You can comment out the exception in UserController, or just leave it. For this example, we only want to test roleController